// (async function(){
//   const mysql = require('mysql2/promise');
//   // 连接数据库
//   const connection = await mysql.createConnection({
//     host: '127.0.0.1',
//     user: 'root',
//     password: '',
//     database: 'test'
//   })
//   // arr 返回一个数组，第一个数组是表的值，
//   // 第二个数组是记录中包含的字段的信息
//   let [users] = await connection.query("SELECT username,age FROM users")
//   console.log(users);
//   users.forEach(user => {
//     console.log(user.name);
//   })

// })();

(async function() {

const Koa = require('koa')
const Static = require('koa-static-cache')
const Router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const Mysql = require('mysql2/promise')

const app = new Koa()

app.use(Static('./static', {
  prefix: '/static',
  gzip: true
}))

app.use(bodyParser())

const connection = await Mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  password: '',
  database: 'test'
})
const router = new Router()
router.get('/todos', async (ctx, next) => {
 // 读取数据库
 const [data] = await  connection.query("SELECT id,title,done FROM todos ORDER BY done ASC, id DESC")
 
 ctx.body = {
   code: 0,
   data
 }

})

router.post('/add', async (ctx, next) => {
  const title = ctx.request.body.title || ''
  // 编辑数据库，新增数据
  const [rs] = await connection.query("INSERT INTO todos (title, done) VALUES ('"+ title +"', 0)")
  // 判断数据插入成功
  if(rs.affectedRows > 0) {
    ctx.body = {
      code: 0,
      data: '添加成功'
    }
  } else {
    ctx.body = {
      code: 2,
      data: '添加失败'
    }
  }

})

app.use(router.routes())

app.listen(80)


})()
